package com.triumphxx.langchain4j.service.impl;

import com.triumphxx.langchain4j.Config.DeepSeekConfig;
import com.triumphxx.langchain4j.service.AIService;
import dev.langchain4j.memory.ChatMemory;
import dev.langchain4j.memory.chat.MessageWindowChatMemory;
import dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.service.AiServices;
import jakarta.annotation.PostConstruct;
import lombok.Getter;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author:triumphxx
 * @Date: 2025/7/24
 * @Time: 14:15
 * @微信公众号：思考集结处
 * @网站：http://blog.triumphxx.com.cn
 * @GitHub https://github.com/triumphxx
 * @Desc: ds实现
 **/
@Service
public class DeepSeekService {
    private final ChatLanguageModel chatModel;
    private final DeepSeekConfig config;
    private AIService aiService;

    @Getter
    private final Map<String, ChatMemory> chatMemories = new HashMap<>();

    public DeepSeekService(ChatLanguageModel chatModel, DeepSeekConfig config) {
        this.chatModel = chatModel;
        this.config = config;
    }

    @PostConstruct
    public void init() {
        this.aiService = AiServices.builder(AIService.class)
                .chatLanguageModel(chatModel)
                .chatMemoryProvider(contextId ->
                        chatMemories.computeIfAbsent(
                                (String) contextId,
                                id -> MessageWindowChatMemory.withMaxMessages(20)
                        )
                )
                .build();
    }

    public String chat(String contextId, String message) {
        try {
            return aiService.chat(contextId, message);
        } catch (dev.ai4j.openai4j.OpenAiHttpException e) {
            if (e.getMessage().contains("Insufficient Balance")) {
                // 处理余额不足的情况
                throw new RuntimeException("API服务余额不足，请联系管理员充值", e);
            }
            throw e;
        }
    }

    public String generateCode(String contextId, String topic) {
        return aiService.generateCode(contextId, topic);
    }

    public String createNewContext() {
        return UUID.randomUUID().toString();
    }

    public void clearContext(String contextId) {
        chatMemories.remove(contextId);
    }
}
